#!/bin/bash

function cavan_visual_command()
{
	echo -e "\033[1mExecute: $*\033[0m"

	$* || return 1

	return 0
}

function sprd_compile_once()
{
	[ "$1" ] || return 1

	if [ -d "3rdparty" ]
	then
		cavan_visual_command rm out/target/common -rf
		cavan_visual_command ./mk -o=2sim $1 n
		ln -vsf out/target/product/hsdroid .
	else
		source build/envsetup.sh
		cavan_visual_command lunch $1 || return 1

		[ -d "device/sprd" ] &&
		{
			cavan_visual_command kheader || return 1
		}

		cavan_visual_command make update-api -j${MAKE_JOBS} || return 1
		cavan_visual_command make -j${MAKE_JOBS} || return 1
		ln -vsf out/target/product/* .
	fi

	return 0
}

[ -f "$1" ] ||
{
	(sprd_compile_once $1) || exit 1
	exit 0
}

while read line
do
	[[ "${line}" == \#* ]] && continue

	set $line

	cavan_visual_command cd $1 || continue
	cavan_visual_command cavan-git-svn-repo init || continue
	cavan_visual_command cavan-git-svn-repo sync || continue
	cavan_visual_command cavan-git-svn-repo symlink

	[ $# -gt 1 ] && cavan_visual_command rm out *.pac -rf

	while :
	do
		shift
		[ "$1" ] || break
		(sprd_compile_once $1) > $1-compile.log 2>$1-error.log
	done

	for fn in u-boot/u-boot-*.bin u-boot/nand_fdl/fdl2.bin u-boot/nand_spl/u-boot-spl-16k.bin
	do
		[ -e "${fn}" ] || continue
		ln -vsf "${fn}" .
	done
done < $1
